﻿using DDD.Core.Const;
using DDD.Core.DependencyInjection;
using DDD.Domain.Entities;
using DDD.Domain.Repositories;
using FluentValidation;

namespace DDD.Application.Commands.UserCommand.UpdateUserById
{
    public class UpdateUserByIdCommandValidate : AbstractValidator<UpdateUserByIdCommand>
    {
        public UpdateUserByIdCommandValidate()
        {
            User user = default;

            RuleFor(c => c.Id).NotNull()
                .Must(c => UserIsExist(c, out user))
                .WithMessage(c => $"不存在主键是：{c.Id}的");

            RuleFor(c => c.UserName).NotEmpty()
                .NotNull().MinimumLength(5)
                .Must(c =>
                {
                    if (user!.UserName != c)
                        return BeUniqueUserName(c);

                    return true;
                })
                .WithMessage(c => $"用户名：{c.UserName}已经被注册");

            RuleFor(c => c.Password).NotEmpty()
               .NotNull().MinimumLength(5);

            RuleFor(c => c.Email).NotNull().When(c => !string.IsNullOrEmpty(c.Email))
                .Matches(RegexConst.EMAIL);

            RuleFor(c => c.Phone).NotNull().When(c => !string.IsNullOrEmpty(c.Phone))
                .Matches(RegexConst.PHONE);
        }

        private bool UserIsExist(Guid id, out User? user)
        {
            user = IOC.Resolve<IUserRepository>().Query(c => c.Id == id).FirstOrDefault();

            return user != null;
        }

        private bool BeUniqueUserName(string username)
          => IOC.Resolve<IUserRepository>().Query(c => c.UserName == username).FirstOrDefault() == null;
    }
}
